<template>
  <!-- 头部区域 -->
  <van-nav-bar
    :title="`购物车(${carsNum})`"
    left-text="返回"
    left-arrow
    @click-left="$router.go(-1)"
  />
  <!-- 购物车区域 -->
  <van-empty v-if="carList.length === 0" description="购物车暂无内容" />
  <div class="car-buy-list carGoodslist" v-else>
    <div
      class="car-buy-item carGoods"
      v-for="item in carList"
      :key="item.proid"
    >
      <van-swipe-cell>
        <van-cell :border="false">
          <van-checkbox
            class="buy-item-checkbox"
            v-model="item.check"
            icon-size="24px"
            @change="changeItem"
          ></van-checkbox>
          <div class="buy-item-right">
            <div class="item-right-img">
              <img class="right-img" :src="item.img1" alt="" />
            </div>
            <div class="item-right-content">
              <div class="right-text">{{ item.proname }}</div>
              <div class="right-price">
                <div class="price-price">￥{{ item.originprice }}</div>
                <div class="price-num">
                  <van-stepper
                    v-model="item.num"
                    theme="round"
                    button-size="22"
                    disable-input
                    :name="item.proid"
                    @change="changeGoodsNum"
                    @plus="increaseNum(item)"
                    @minus="dwindleNum(item)"
                  />
                </div>
              </div>
            </div>
          </div>
        </van-cell>
        <template #right>
          <van-button
            @click="delGoods(item)"
            square
            type="danger"
            text="删除"
            class="deleteGoods"
          />
        </template>
      </van-swipe-cell>
    </div>
  </div>
  <van-divider class="car-divider">可能还想要</van-divider>
  <!-- 推荐商品区域 -->
  <van-pull-refresh
    class="goods-refresh"
    v-model="refreshLoading"
    @refresh="onRefresh"
  >
    <div class="goods-list">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        class="goods-item"
      >
        <van-cell
          v-for="item in productList"
          :key="item.proid"
          @click="goToDetail(item.proid)"
        >
          <div class="item-imgbox">
            <img :src="item.img1" alt="" />
          </div>
          <div>
            <p>{{ item.proname }}</p>
            <p>￥{{ item.originprice }}</p>
          </div>
        </van-cell>
      </van-list>
    </div>
  </van-pull-refresh>
  <!-- 订单提交区域 -->
  <van-submit-bar
    :price="totalPrice"
    button-text="提交订单"
    @submit="onSubmit"
    class="dingdantijiao"
  >
    <van-checkbox @click="changeCheckAll" v-model="checkedAll"
      >全选</van-checkbox
    >
  </van-submit-bar>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import type { Ref } from "vue";
import { delCarts, lookCarts, updatenum } from "@/api/api";
import { useProductList } from "@/hooks/HomeViewHook";
import { toRaw } from "@vue/reactivity";

interface ICarItem {
  proid: string;
  check: boolean;
  img1: string;
  proname: string;
  originprice: number;
  num: number;
  cartid: string;
}
const {
  refreshLoading,
  onRefresh,
  loading,
  finished,
  onLoad,
  productList,
  goToDetail,
} = useProductList();
const showFlag: Ref<boolean> = ref(true);
const carList: Ref<ICarItem[]> = ref([]);
const checkAll: Ref<boolean> = ref(false);
const carsNum: Ref<number> = ref(0);
const checkedAll: Ref<boolean> = ref(false);

const changeGoodsNum = () => {
  console.log("changeGoodsNum");
};

const APIcarList = async () => {
  const res = await lookCarts({
    userid: localStorage.getItem("userId"),
  });
  // console.log(res);
  // console.log(res.data);

  if (res.data) {
    carList.value = res.data;
    carList.value = JSON.parse(JSON.stringify(carList.value));
    //  console.log(carList.value);
  } else {
    showFlag.value = false;
  }
  carsNum.value = carList.value.length;
};

const dwindleNum = async (item: any) => {
  console.log(item);

  const res = await updatenum({
    cartid: item.cartid,
    num: item.num - 0 - 1,
  });
  APIcarList();
};
const increaseNum = async (item: any) => {
  const res = await updatenum({
    cartid: item.cartid,
    num: item.num - 0 + 1,
  });
  APIcarList();
};
const delGoods = async (item: any) => {
  const res = await delCarts({
    cartid: item.cartid,
  });
  APIcarList();
};

const totalPrice = computed(() => {
  let tmp = 0;
  // console.log(carList.value);
  carList.value.forEach((item) => {
    if (item.check) {
      tmp += item.originprice * item.num * 100;
    }
  });
  return tmp;
});

const onSubmit = () => {
  console.log("提交订单");
};

// 让全选按钮和单个数据联动
const checkedSelect = () => {
  // 排它法
  // 首先假设数据都被勾选了，于是直接给checkedAll变为true
  checkedAll.value = true;
  // 然后再去循环真实的数据，一旦有一个数据没有被勾选，那么直接把checkedAll变成false
  console.log(carList.value);

  carList.value.forEach((v) => {
    if (!v.check) {
      checkedAll.value = false;
      return false;
    }
  });
};

// 点击全选的时候触发
const changeCheckAll = () => {
  carList.value.forEach((v) => {
    v.check = checkedAll.value;
  });
};

// 点击购物车内单个数据的勾选框时触发
const changeItem = (checked: boolean) => {
  // checked如果是false，说明有一个选项被取消了，那么直接把chechedAll变成false就好；如果checked是true，说明当前这一项被选中了，那么就需要考虑是否其他的选项也被选中了，其他选项中但凡有一个false，checkedAll就只能是false，如果全部是true，那么checkedAll就得变成true
  !checked ? (checkedAll.value = false) : checkedSelect();
  // if (!checked) {
  //   checkedAll.value = false;
  // } else {
  //   checkedSelect();
  // }
};
onMounted(() => {
  APIcarList();
  // changeCheckAll()
});
</script>

<style lang="scss" scoped>
.car-divider {
  &::after,
  &::before {
    background-color: #23232382;
  }
}
.car-goods-list {
  display: flex;
  flex-flow: wrap;
  justify-content: space-evenly;
  background-color: rgba(75, 84, 75, 0.12);
  padding-bottom: 100px;
  .van-cell {
    width: 48%;
    margin: 10px 0;
    .car-goods-item {
      .item-img {
        img {
          display: block;
          width: 100%;
          height: 100%;
        }
      }
      .item-text {
        display: -webkit-box;
        text-overflow: ellipsis;
        text-align: left;
        overflow: hidden;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        word-break: break-all;
        color: #222;
        margin: 10px 0;
      }
      .item-price {
        text-align: left;
        font-weight: bold;
        color: rgb(227, 37, 28);
      }
    }
  }
}
.car-buy-list {
  .car-buy-item {
    border-bottom: 1px solid #23232326;
    &:nth-last-child(1) {
      border: none;
    }
    margin-bottom: 20px;
    .van-swipe-cell {
      :deep(.van-swipe-cell__wrapper) {
        .van-cell {
          .van-cell__value {
            display: flex;
            .buy-item-checkbox {
              overflow: visible;
            }
            .buy-item-right {
              display: flex;
              margin-left: 40px;
              .item-right-img {
                height: 160px;
                width: 200px;
                margin-right: 30px;
                border-radius: 10px;
                overflow: hidden;
                .right-img {
                  width: 100%;
                  height: 100%;
                }
              }
              .item-right-content {
                .right-text {
                  display: -webkit-box;
                  text-overflow: ellipsis;
                  text-align: left;
                  overflow: hidden;
                  -webkit-box-orient: vertical;
                  -webkit-line-clamp: 2;
                  word-break: break-all;
                  font-size: 12px;
                  line-height: 30px;
                  color: #222;
                  margin-top: 10px;
                }
                .right-price {
                  display: flex;
                  justify-content: space-between;
                  margin-top: 50px;
                }
              }
            }
          }
        }
        .van-swipe-cell__right {
          .van-button {
            height: 100%;
          }
        }
      }
    }
  }
}

.goods-refresh {
  overflow: inherit;
  .goods-list {
    display: flex;
    width: 100%;
    .goods-item {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-evenly;
      width: 100%;
      margin: 10px;
      border-radius: 10px;
      margin: 8px 0;
      overflow: hidden;
      .van-cell {
        width: 48%;
        margin-top: 10px;
      }
      .item-imgbox {
        width: 100%;
        img {
          display: block;
          width: 100%;
        }
      }
    }
  }
}
</style>
